﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Text;
using Thor.Common;

namespace Thor.Repository.EntFx
{
    public class MessageRepository : RepositoryBase, IMessageRepository
    {
        #region Constructors

        public MessageRepository(Dictionary<string, object> repositoryParameters)
            : base(repositoryParameters) { }

        #endregion

        #region IMessageRepository Members

        public void Insert(Message message)
        {
            if (message != null && Model != null)
            {
                var entity = CreateEntityFromPoco(message);
                Model.AddToQueueEntities(entity);
                Model.SaveChanges();
            }
        }

        public Message Fetch()
        {
            var message = Peek();

            if (message != null)
                Delete(message);

            return message;
        }

        public Message Peek()
        {
            if (Model != null)
            {
                var entity = Model.QueueEntities.FirstOrDefault();

                if (entity != null)
                    return CreatePocoFromEntity(entity);
                else
                    return null;
            }

            return null;
        }

        public void Delete(Message message)
        {
            if (message != null && Model != null)
            {
                var entity = Model.QueueEntities.Where(q => q.Id == message.Id).FirstOrDefault();

                if (entity != null)
                {
                    Model.DeleteObject(entity);
                    Model.SaveChanges();
                }
            }
        }

        public void Clear()
        {
            var query = Model.QueueEntities.ToList();

            foreach (var item in query)
            {
                var message = CreatePocoFromEntity(item);
                Delete(message);
            }
        }

        #endregion

        #region Methods

        private QueueEntity CreateEntityFromPoco(Message poco)
        {
            QueueEntity entity = new QueueEntity();

            entity.Id = string.IsNullOrEmpty(poco.Id) ? Guid.NewGuid().ToString() : poco.Id;
            entity.Message = poco.Text;

            return entity;
        }

        private Message CreatePocoFromEntity(QueueEntity entity)
        {
            Message poco = new Message();

            poco.Id = entity.Id;
            poco.Text = entity.Message;

            return poco;
        }

        #endregion
    }
}